package com.yuhong.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuhong.springbootinit.common.BaseResponse;
import com.yuhong.springbootinit.common.ResultUtils;
import com.yuhong.springbootinit.constant.CommonConstant;
import com.yuhong.springbootinit.mapper.CompanyMapper;
import com.yuhong.springbootinit.model.dto.company.CompanyQueryRequest;
import com.yuhong.springbootinit.model.dto.company.PositionCompanyDTO;
import com.yuhong.springbootinit.model.entity.Company;
import com.yuhong.springbootinit.model.entity.Position;
import com.yuhong.springbootinit.service.CompanyService;
import com.yuhong.springbootinit.service.PositionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @BelongsProject: resume-analysis-system
 * @BelongsPackage: com.yuhong.springbootinit.controller
 * @Author: renyuhong
 * @CreateTime: 2025-04-17  23:22
 * @Description:
 * @Version: 1.0
 */

@RestController
@RequestMapping("/company")
@Slf4j
public class CompanyController {

    @Resource
    private CompanyService companyService;

    @Resource
    private PositionService positionService;

    @Resource
    private CompanyMapper companyMapper;


    @PostMapping("/list/page")
    public BaseResponse<Page<Company>> listCompaniesByPage(@RequestBody CompanyQueryRequest queryRequest) {
        long current = queryRequest.getCurrent();
        long pageSize = queryRequest.getPageSize();
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder();

        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(queryRequest.getCompanyName())) {
            queryWrapper.like("company_name", queryRequest.getCompanyName());
        }

        if (StringUtils.isNotBlank(queryRequest.getLocation())) {
            queryWrapper.eq("location", queryRequest.getLocation());
        }
        if(StringUtils.isNotBlank(queryRequest.getTag())){
            queryWrapper.like("tag",  queryRequest.getTag());
        }

        if (StringUtils.isNotBlank(sortField)) {
            boolean isAsc = CommonConstant.SORT_ORDER_ASC.equals(sortOrder);
            queryWrapper.orderBy(true, isAsc, sortField);
        }

        return ResultUtils.success(companyService.page(new Page<>(current, pageSize), queryWrapper));
    }


    @GetMapping("/list/position")
    public BaseResponse<List<Position>> listByCompanyId(@RequestParam String companyId) {
        List<Position> positionList = positionService.getPositionListByCompanyId(companyId);
        return ResultUtils.success(positionList);
    }

    @GetMapping("/list/position/with/company")
    public BaseResponse<List<PositionCompanyDTO>> listPositionWithCompany() {
        List<PositionCompanyDTO> allPositionCompanyInfo = companyService.getAllPositionCompanyInfo();
        return ResultUtils.success(allPositionCompanyInfo);
    }

    @PostMapping("/importZip")
    public ResponseEntity<String> importCompanies(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty() || !file.getOriginalFilename().endsWith(".zip")) {
            return ResponseEntity.badRequest().body("请上传一个有效的 ZIP 文件");
        }

        try {
            File tempFile = File.createTempFile("company_logos", ".zip");
            file.transferTo(tempFile); // 将 MultipartFile 转为本地临时文件

            importCompaniesFromZip(tempFile); // 调用导入逻辑
            tempFile.delete(); // 清理临时文件

            return ResponseEntity.ok("公司数据导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("导入失败：" + e.getMessage());
        }
    }

    public void importCompaniesFromZip(File zipFile) throws IOException {
        List<String> hotCities = Arrays.asList(
                "北京", "上海", "广州", "深圳", "杭州", "成都", "南京", "武汉", "西安", "苏州"
        );
        Random random = new Random();

        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile))) {
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                if (!entry.isDirectory() && isImage(entry.getName())) {
                    String fileName = new File(entry.getName()).getName();
                    String companyId = fileName.substring(0, fileName.lastIndexOf('.'));

                    Company company = new Company();
                    company.setCompanyId(companyId);
                    company.setCompanyName("公司名_" + companyId);
                    company.setLocation(hotCities.get(random.nextInt(hotCities.size())));

                    companyMapper.insert(company);
                }
            }
        }
    }


    private boolean isImage(String fileName) {
        return fileName.toLowerCase().endsWith(".jpg")
                || fileName.toLowerCase().endsWith(".png")
                || fileName.toLowerCase().endsWith(".jpeg");
    }

}
